package com.example.coursedesign.utils;

import android.os.AsyncTask;
import android.util.Log;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * function： 数据库工具类，连接数据库用
 */
public class JDBCUtils {
    private static final String TAG = "mysql-coursedesign-JDBCUtils";

    private static final String DRIVER = "com.mysql.cj.jdbc.Driver"; // 新的MySQL驱动类名
    private static final String DB_NAME = "as_javaee_coursedesign"; // 数据库名称
    private static final String USER = "root"; // 用户名
    private static final String PASSWORD = "123456"; // 密码
    private static final String IP = "192.168.93.1"; // 本机IP地址

    static {
        try {
            Class.forName(DRIVER); // 动态加载类
        } catch (ClassNotFoundException e) {
            Log.e(TAG, "Database driver loading failed: " + e.getMessage());
        }
    }

    /**
     * 获取数据库连接
     */
    public static Connection getConn() {
        Connection connection = null;
        try {
            // 尝试建立到给定数据库URL的连接
            connection = DriverManager.getConnection(
                    "jdbc:mysql://" + IP + ":3309/" + DB_NAME + "?useUnicode=true&characterEncoding=UTF-8&useSSL=false",
                    USER, PASSWORD
            );
            Log.d(TAG, "Database connection successful: " + connection);
        } catch (SQLException e) {
            Log.e(TAG, "Database connection failed: " + e.getMessage());
        }
        return connection;
    }

    /**
     * 关闭数据库连接
     */
    public static void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
                Log.d(TAG, "Database connection closed.");
            } catch (SQLException e) {
                Log.e(TAG, "Failed to close database connection: " + e.getMessage());
            }
        }
    }

    // 使用AsyncTask来确保数据库操作不在主线程中执行
    public static class DatabaseTask extends AsyncTask<Void, Void, Connection> {

        @Override
        protected Connection doInBackground(Void... params) {
            return getConn();
        }

        @Override
        protected void onPostExecute(Connection connection) {
            super.onPostExecute(connection);
            // 在这里可以进行进一步的逻辑处理
        }
    }

}